package com.stevenxin.controller;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.stevenxin.pojo.Users;
import com.stevenxin.service.IUserService;
import com.stevenxin.utils.JSONResult;
import com.stevenxin.utils.MD5Utils;
import com.stevenxin.vo.UsersVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value="用户注册登录的接口", tags= {"注册和登录的controller"})
public class RegistLoginController extends BasicController {
	
	@Autowired
	IUserService userService;
	
	@ApiOperation(value="用户注册", notes="用户注册接口api")
	@PostMapping("/regist")
	public JSONResult regist(@RequestBody Users user) throws Exception {
		if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return JSONResult.errorMsg("用户名或密码为空");
		}
		boolean userNameIsExist=userService.queryUserNameIsExist(user.getUsername());
		if(userNameIsExist) {
			return JSONResult.errorMsg("用户名已经存在");
		}else {
			user.setNickname(user.getUsername());
			user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
			user.setReceiveLikeCounts(0);
			user.setFansCounts(0);
			user.setFollowCounts(0);
			userService.saveUser(user);
			UsersVO userVo=setUsersVO(user);
			return JSONResult.ok(userVo);
		}
		
		
	}
	
	@ApiOperation(value="用户登录", notes="用户登录API")
	@PostMapping("/login")
	public JSONResult login(@RequestBody Users user) throws Exception {
		if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return JSONResult.errorMsg("用户名或密码为空");
		}
		user=userService.queryUserForLogin(user.getUsername(), MD5Utils.getMD5Str(user.getPassword()));
		if(user==null) {
			return JSONResult.errorMsg("用户名或密码错误");
		}
		UsersVO userVo=setUsersVO(user);
		return JSONResult.ok(userVo);
	}
	
	@ApiOperation(value="用户注销", notes="用户注销API")
	@ApiImplicitParam(name="userId", value="用户ID", required=true, dataType="String", paramType="query")
	@PostMapping("/logout")
	public JSONResult logout(String userId) throws Exception {
		redis.del(REDIS_USER_SESSION+":"+userId);
		return JSONResult.ok("注销成功");
	}
	
	public UsersVO setUsersVO(Users user) {
		String token=UUID.randomUUID().toString();
		redis.set(REDIS_USER_SESSION+":"+user.getId(), token, 1000*60*30);
		UsersVO userVo=new UsersVO();
		BeanUtils.copyProperties(user, userVo);
		userVo.setUserToken(token);
		return userVo;
	}
	
}
